package com.threegroup.admin.controller;


import com.github.pagehelper.PageInfo;
import com.threegroup.admin.annotation.AuthorityVerify.AuthorityVerify;
import com.threegroup.admin.dto.DishDTO;
import com.threegroup.admin.entity.DishEntity;
import com.threegroup.admin.entity.DishFlavorEntity;
import com.threegroup.admin.service.DishService;
import com.threegroup.admin.utils.RabbitMqRecive;
import com.threegroup.admin.utils.RabbitMqSend;
import com.threegroup.common.constant.Constant;
import com.threegroup.common.utils.Result;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Update;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("takeout/dish")
public class DishController {
    @Resource
    private DishService dishService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @AuthorityVerify("takeout:dish:update")
    @PutMapping("updateStatus")
    public Result upDateStatus(@RequestBody List<String> ids,HttpServletRequest request){

        dishService.upDateStatus(ids);
        return new Result();
    }
    /**
     * 保存菜品
     * @param dishDTO
     * @param request
     * @return
     */
    @AuthorityVerify("takeout:dish:save")
    @PostMapping
    public Result saveDish(@RequestBody DishDTO dishDTO, HttpServletRequest request) {
        //获取该请求的ID
        String  id = (String) request.getAttribute(Constant.USER_ID);

        //添加id
        dishDTO.setCreator(Long.valueOf(id));
        dishDTO.setUpdater(Long.valueOf(id));

        //获取该请求的Ip
        String ip = getIP(request);
        ip+="save";
        //校验幂等性
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        stringRedisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        //检查redis存在与否
        DishDTO save = (DishDTO) opsForHash.get(ip, "save");
        if (dishDTO!=null){
            if (dishDTO.equals(save)){
                Result result = new Result();
                result.setMsg("已执行，勿要重复提交");
                //重置时长3秒
                stringRedisTemplate.expire(ip,3,TimeUnit.SECONDS);
                return result;
            }
        }

        dishService.saveDish(dishDTO);


        //将刚刚保存的信息设置到redis，并设置有效时间
        //存入redis
        opsForHash.put(ip,"save",dishDTO);
        //设置时长3秒
        stringRedisTemplate.expire(ip,3,TimeUnit.SECONDS);
        return new Result();
    }

    /**
     * 更新菜品
     * @param dishDTO
     * @param request
     * @return
     */
    @AuthorityVerify("takeout:dish:update")
    @PutMapping
    public Result updateDish(@RequestBody DishDTO dishDTO,HttpServletRequest request) {
        //获取该请求的ID
        String  id = (String) request.getAttribute(Constant.USER_ID);
        id="1067246875800000001";
        dishDTO.setUpdater(Long.valueOf(id));
        //获取该请求的ID
        String ip = getIP(request);
        ip+="update";
        //校验幂等性
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        stringRedisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        //检查redis存在与否
        DishDTO save = (DishDTO) opsForHash.get(ip, "update");
        if (dishDTO!=null){
            if (dishDTO.equals(save)){
                Result result = new Result();
                result.setMsg("已执行，勿要重复提交");
                //重置时长3秒
                stringRedisTemplate.expire(ip,3,TimeUnit.SECONDS);
                return result;
            }
        }

        dishService.updateDish(dishDTO);


        //将刚刚保存的信息设置到redis，并设置有效时间
        //存入redis
        opsForHash.put(ip,"update",dishDTO);
        //设置时长3秒
        stringRedisTemplate.expire(ip,3,TimeUnit.SECONDS);


        return new Result();
    }

    /**
     * 删除菜品
     * @param ids
     * @param request
     * @return
     */
    @AuthorityVerify("takeout:dish:delete")
    @DeleteMapping
    public Result deleteDish(@RequestBody List<String> ids,HttpServletRequest request) {

        //获取该请求的ID
        String ip = getIP(request);
        ip+="delete";
        //校验幂等性
        HashOperations<String, String, String> opsForHash = stringRedisTemplate.opsForHash();
        stringRedisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        //检查redis存在与否
        String save =  opsForHash.get(ip, "delete");

        String s1 = ids.toString();
        if (s1!=null){
            if (ids.equals(save)){
                Result result = new Result();
                result.setMsg("已执行，勿要重复提交");
                //重置时长3秒
                stringRedisTemplate.expire(ip,3,TimeUnit.SECONDS);
                return result;
            }
        }
        //执行删除

            dishService.deleteDish(ids);



        //将刚刚保存的信息设置到redis，并设置有效时间
        //存入redis
        opsForHash.put(ip,"delete",s1);
        //设置时长3秒
        stringRedisTemplate.expire(ip,3,TimeUnit.SECONDS);
       return new Result();
    }

    /**
     * 提供共给商家的查询方式
     * @param dishDTO
     * @return
     */
    @GetMapping("list")
    public Result<List<DishDTO>> queryDish(@RequestBody DishDTO dishDTO) {

        Result<List<DishDTO>> dishDTOResult = dishService.queryDishByAll(dishDTO);
        return dishDTOResult;
    }

    /**
     * 分页查询提供给后台商家
     * @param limit
     * @param page
     * @param order
     * @param orderField
     * @return
     */
    @AuthorityVerify("takeout:dish:page")
    @GetMapping("page")
    public Result<PageInfo<DishEntity>> pageInfoResult(Integer limit, Integer page, String order, String orderField,String id ){
        //在此处开启消息队列接收
        try {
            new RabbitMqRecive().run();
            new RabbitMqSend().run();
            System.out.println("开启了消息队列消费端");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Result<PageInfo<DishEntity>> result= dishService.getDishList(limit,page,order,orderField,id);
        return result;
    }

        /**
         * 查Id
         * @param id
         * @return
         */
    @AuthorityVerify("takeout:dish:info")
    @GetMapping("{id}")
    public Result<DishDTO> queryDishById(@PathVariable String id) {
        Result<DishDTO> result = dishService.queryDishById(id);
        return result;
    }

    /**
     * 获取该请求的ip地址
     * @param request
     * @return
     */
    public String getIP(HttpServletRequest request){
        String remoteAddr = request.getRemoteAddr();
        String ip="";
        String[] split = remoteAddr.split(":");
        for (String s : split) {
            ip+=s;
        }
        return ip;
    }
}
